package com.hand.wfive.loginAndVip;

import static android.content.Context.MODE_PRIVATE;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hand.wfive.App;
import com.hand.wfive.R;
import com.hand.wfive.ad.AdConfig;
import com.hand.wfive.entity.event.EventBusBean;
import com.hand.wfive.entity.event.EventTagConfig;
import com.hand.wfive.loginAndVip.model.ApiModel;
import com.hand.wfive.loginAndVip.model.User;
import com.hand.wfive.loginAndVip.model.UserEvent;
import com.hand.wfive.loginAndVip.model.UserRefreshEvent;
import com.hand.wfive.util.DateUtils;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.observers.ResourceObserver;
import rxhttp.wrapper.param.RxHttp;

public class UserManager {

    private static final String SharedName = "userShared";
    private static final String SharedKey = "user";

    public static final String LoginType_normal = "1";
    public static final String LoginType_wechat = "2";
    // public static final String LoginType_qq = "3";
    public static final String LoginType_huawei = "4";
    public static final String LoginType_mobile = "5";
    public static final String LoginType_code = "6";

    private UserManager() {
    }

    private static final class Holder {
        private static final UserManager userManager = new UserManager();
    }

    public static UserManager getInstance() {
        return Holder.userManager;
    }

    private User curUser;

    public void initUser() {
        initUser(true);
    }

    public void initUser(boolean fetch) {
        SharedPreferences pref = App.getContext().getSharedPreferences(SharedName, MODE_PRIVATE);
        String json = pref.getString(SharedKey, "");
        try {
            curUser = new Gson().fromJson(json, User.class);
            if (curUser != null && curUser.getIsVip() == 1) {
                AdConfig.isShowAd = false;
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        //同步后台数据
        if (fetch) fetchUser();
    }
    public void saveUser(User user) {
        saveUser(user, true);
    }

    private void saveUser(User user, boolean isNotifyRefreshUser) {
        if (user == null) {
            return;
        }
        try {
            SharedPreferences pref = App.getContext().getSharedPreferences(SharedName, MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            curUser = user;
            if (curUser.getIsVip() == 1) {
                AdConfig.isShowAd = false;
            }
            String json = new Gson().toJson(user);
            editor.putString(SharedKey, json);
            editor.apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isNotifyRefreshUser) EventBus.getDefault().post(new UserEvent());
    }

    public void deleteUserVip() {
        User user = getCurUser();
        user.setIsVip(0);
        saveUser(user, false);
        EventBus.getDefault().post(new EventBusBean(EventTagConfig.TAG_REFRESH_USER_STATUS));
    }

    public boolean isLogin() {
        return curUser != null;
    }

    public void logOut() {
        AdConfig.isShowAd = true;
        curUser = null;
        SharedPreferences pref = App.getContext().getSharedPreferences(SharedName, MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(SharedKey, "");
        editor.apply();
        EventBus.getDefault().post(new UserEvent());
        MobileLogin.getInstance().clearScripCache();
    }

    public boolean isVip() {
        if (curUser == null) {
            return false;
        }
        return curUser.getIsVip() == 1;
    }

    public String getUserId() {
        if (curUser == null) {
            return "";
        }
        return curUser.getId();
    }


    public String getVipEndTime() {
        if (TextUtils.isEmpty(curUser.getVipDay())) {
            return "";
        }
        int vipDay = Integer.parseInt(curUser.getVipDay());
        if (vipDay >= 0) {
            return "有效期至：" + DateUtils.getAfterDay(vipDay);
        } else {
            return "您已是永久会员";
        }
    }

    public String getVipDayDesc() {
        if (TextUtils.isEmpty(curUser.getVipDay())) {
            return "";
        }
        int vipDay = Integer.parseInt(curUser.getVipDay());
        if (vipDay >= 0) {
            return "会员剩余:" + vipDay+"天";
        } else {
            return "会员剩余:永久";
        }
    }

    /**
     * 获取vip描述
     *
     * @return
     */
    public String getVipTypeText() {
        if (curUser == null) {
            return "";
        }
        return VipConfig.getVipLableByValue(curUser.getVipType());
    }

    public int getVipTimes() {
        if (curUser == null) {
            initUser();
            if (curUser == null)
                return 0;
        }
        if (TextUtils.isEmpty(curUser.vipTimes))
            return 0;
        try {
            return Integer.parseInt(curUser.vipTimes);
        } catch (Exception e) {
            return 0;
        }
    }

    public User getCurUser() {
        return curUser;
    }

    private void fetchUser() {
        if (curUser != null && !TextUtils.isEmpty(curUser.getPassword())) {
            if (curUser.isOpenVipFaild() && !TextUtils.isEmpty(curUser.getVipType())
                    && !TextUtils.isEmpty(curUser.getOrderNo())) {
                RxHttp.postForm(ApiConfig.modifyVip)
                        .add("appid", LoginConfig.AppId)
                        .add("username", curUser.getUsername())
                        .add("psw", curUser.getPassword())
                        .add("vipType", curUser.getVipType())
                        .add("orderNo", curUser.getOrderNo())
                        .asClass(ApiModel.class)
                        .doFinally(() -> EventBus.getDefault().post(new UserRefreshEvent()))
                        .subscribe(new ResourceObserver<ApiModel>() {
                            @Override
                            public void onNext(@NonNull ApiModel apiModel) {
                                if (apiModel.getCode() == ApiConfig.SUCCESSCODE) {
                                    User user = apiModel.getObj();
                                    user.setPassword(curUser.getPassword());
                                    UserManager.getInstance().saveUser(user);
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                EventBus.getDefault().post(new UserRefreshEvent());
                            }
                        });
            } else {
                RxHttp.postForm(ApiConfig.login)
                        .add("appid", LoginConfig.AppId)
                        .add("username", curUser.getUsername())
                        .add("pwd", curUser.getPassword())
                        .add("loginType", curUser.getLoginType())
                        .add("appname", App.getContext().getString(R.string.app_name))
                        .add("packageName", App.getContext().getPackageName())
                        .asClass(ApiModel.class)
                        .doFinally(() -> EventBus.getDefault().post(new UserRefreshEvent()))
                        .subscribe(new ResourceObserver<ApiModel>() {
                            @Override
                            public void onNext(@NonNull ApiModel apiModel) {
                                if (apiModel.getCode() == ApiConfig.SUCCESSCODE) {
                                    User user = apiModel.getObj();
                                    user.setPassword(curUser.getPassword());
                                    UserManager.getInstance().saveUser(user);
                                } else if (apiModel.getCode() == ApiConfig.USERCHANGEINFOCODE) {
                                    UserManager.getInstance().deleteUserVip();;
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                EventBus.getDefault().post(new UserRefreshEvent());
                            }
                        });
            }

        }
    }
}
